package think.thread.sychron;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

class FinalVar {
	static int SIZE = 3;
}

class ExchangerProduce implements Runnable {

	Exchanger<List<String>> exchanger;

	List<String> produce = new ArrayList<String>();

	ExchangerProduce(Exchanger<List<String>> exchanger) {
		this.exchanger = exchanger;
		produce.add("one");
		produce.add("two");
		produce.add("three");
	}

	public void run() {
		try {
			List<String> values = exchanger.exchange(produce);
			System.out.println("produce get values:" + values);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

class ExchangerConsume implements Runnable {
	private Exchanger<List<String>> exchanger;
	List<String> product;
	List<String> value;

	ExchangerConsume(Exchanger<List<String>> ex) {
		exchanger = ex;
		value = new ArrayList<String>();
		value.add("1");
		value.add("2");
		value.add("3");
	}

	public void run() {
		try {
			product = (List<String>) exchanger.exchange(value);
			System.out.println("consume get values:" + product);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

public class ExchangerDemo2 {
	public static void main(String[] args) throws Exception {
		Exchanger<List<String>> xc = new Exchanger<List<String>>();

		ExecutorService exec = Executors.newCachedThreadPool();
		exec.execute(new ExchangerProduce(xc));
		exec.execute(new ExchangerConsume(xc));

		TimeUnit.SECONDS.sleep(2);
		exec.shutdownNow();
	}
}
